package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.contant.CatcheConstants;
import com.qk.domain.blusiness.BusinessCountDO;
import com.qk.domain.clue.ClueCountDO;
import com.qk.management.aop.annotation.Cacheable;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ReportOverviewService;
import com.qk.vo.portal.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ReportOverviewServiceImpl implements ReportOverviewService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired//创建一个spring data redis对象操作
    private StringRedisTemplate springRedisTemlate;


    private static final String CACHE_PORTAL_KEY_PREFIX = "qk:portal:";

    // 利用Reis优化程序
    // 1. 选择数据类型  选择使用 string类型
    // 2. 操作步骤
    // 2.1 先查询缓存
    // 2.2 如果缓存命中直接返回
    // 2.3 未命中查询数据库，添加数据到缓存
    // 2.4 返回数据
    // 定义Redis缓存key的前缀，使用技巧基于：号连接！

    @Cacheable(
            redisKeyPrefix = CatcheConstants.CACHE_PORTAL_KEY_PREFIX,// rediskey的前缀
            redisKeyExpireTime = 24*60L,// 缓存时间24小时
            redisKeyExpireTimeUnit = TimeUnit.MINUTES// 缓存时间单位= 分钟
    )
    @Override
    public PortalVO getReportOverview() {
        //定义缓存key
        String cacheKey = CACHE_PORTAL_KEY_PREFIX+"reportOverview";

        //前
        /*//先查询缓存(看下是否缓存命中)
        String jsonStrFromRedis=null;
        try {
            jsonStrFromRedis = springRedisTemlate.opsForValue().get(cacheKey);
            if (ObjectUtil.isNotEmpty(jsonStrFromRedis)){
                //如果缓存命中直接返回
                PortalVO portalVO = JSONUtil.toBean(jsonStrFromRedis, PortalVO.class);
                return portalVO;
            }
        } catch (Exception e) {
            log.error("-----查询缓存失败-----", e);
        }*/

        // 未命中查询数据库，添加数据到缓存:
        //获取线索
        ClueCountDO clueCountDO = clueMapper.getClueCountDO();
        //获取商机
        BusinessCountDO businessCountDO = businessMapper.getBusinessCountDO();
        //进行强转融合
        PortalVO portalVO = BeanUtil.copyProperties(clueCountDO, PortalVO.class);
        BeanUtil.copyProperties(businessCountDO, portalVO);

        //后
        /*//将数据添加到缓存
        try {
            String jsonStrToRedis = JSONUtil.toJsonStr(portalVO);
            springRedisTemlate.opsForValue().set(cacheKey, jsonStrToRedis);
        } catch (Exception e) {
            log.error("-----添加缓存失败-----", e);
        }*/

        //返回
        return portalVO;
    }
}
